package com.chen.androidstudy.activity.recycle;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chen.androidstudy.R;
import com.chen.androidstudy.utils.ScreenUtils;

/**
 * @Author: CHong
 * @CreateDate: 2024/9/3 0003
 * @Description:
 */

public class RecycleViewActivity extends AppCompatActivity {
    RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
            if(manager instanceof LinearLayoutManager){
                LinearLayoutManager layoutManager = (LinearLayoutManager) manager;
                int firstVisiblePos = layoutManager.findFirstVisibleItemPosition();
                setViewAplha(layoutManager.findViewByPosition(firstVisiblePos));

                int firstCompletelyVisible = layoutManager.findFirstCompletelyVisibleItemPosition();
                ConstraintLayout view1 = (ConstraintLayout) layoutManager.findViewByPosition(firstCompletelyVisible);
                if(view1 != null){
                    view1.setAlpha(1);
                }
            }
        }
    };

    private void setViewAplha(View view){
        if (view == null )
            return;
        float beginPercent = 0.1f;
        float endValue = 1;
        float p = ScreenUtils.px2dp(this, Math.abs((int) view.getY())) * 1.0f / ScreenUtils.px2dp(this, view.getHeight()) * 1.0f;
        float curPercent = Float.compare(p - beginPercent, 0.0f) < 0 ? 0.0f : p - beginPercent;
        curPercent = Float.compare(1, curPercent * endValue) < 0 ? 1 : curPercent * endValue;
        view.setAlpha(1 - curPercent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycle_view_layout);
        RecyclerView recyclerView = findViewById(R.id.recyclerView);

        recyclerView.addOnScrollListener(mScrollListener);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(new RecycleViewItemAdapter());
    }
}
